'use strict';
/**
 * Created by FreezeSoul on 2015/9/30.
 */
define([
        'angular',
        'adConfig',
        'app/modules/index/define',
        'app/modules/index/services/index',
        'app/modules/index/controllers/index-resource-folder-edit'
    ],
    function (angular, adConfig) {
        angular.module('ad.index')
            .controller('adIndexResourceController', ['$scope', '$rootScope', '_', '$uibModal', '$uibModalInstance', 'FileUploader', 'adIndexEditService', 'item',
                function ($scope, $rootScope, _, $uibModal, $uibModalInstance, FileUploader, service, item) {
                    $scope.item = item;

                    var deleteMark = "[DELETE]";
                    var rootFolderPath = 'static/resource/';
                    var rootFullPath = adConfig.baseServiceUrl + rootFolderPath;
                    var fileSupports = ['flv', 'mp4', 'avi', 'png', 'jpg', 'jpeg', 'gif', 'mp3', 'pdf', 'svg', 'swf', 'xml'];

                    $scope.selectItem = undefined;
                    $scope.supportsArray = fileSupports;

                    $scope.currentPaths = [];
                    $scope.currentChildFolders = [];
                    $scope.currentChildFiles = [];

                    $scope.uploader = new FileUploader();
                    $scope.uploader.removeAfterUpload = true;
                    $scope.uploader.url = adConfig.baseServiceUrl + 'common/resource/upload';
                    $scope.uploader.headers = {
                        'Authorization': 'Bearer ' + $rootScope.currentUser.UserToken
                    };

                    $scope.uploader.formData = [{
                        "filePath": $scope.currentPaths.join(',')
                    }];

                    $scope.uploader.filters.push({
                        name: 'fileName',
                        fn: function (item) {
                            var fileExtension = item.name.split('.').pop();
                            return fileSupports.indexOf(fileExtension.toLowerCase()) > -1;
                        }
                    });

                    $scope.uploader.onAfterAddingFile = function () {
                        angular.element("#resource-upload").val(null);
                    };

                    $scope.uploader.onCompleteAll = function () {
                        $scope.loadChildFolders();
                        $scope.loadChildFiles();
                    };

                    $scope.uploader.onBeforeUploadItem = function (item) {
                        item.formData = [{
                            "filePath": $scope.currentPaths.join(',')
                        }];
                    };

                    $scope.fileSelected = function (file) {
                        $scope.selectItem = file;
                    };

                    $scope.getImageUrl = function (file) {
                        var resourcePng = "app/images/resource-@.png";
                        var fileExtension = file.split('.').pop();
                        if (['png', 'jpg', 'jpeg', 'gif'].indexOf(fileExtension.toLowerCase()) == -1) {
                            return resourcePng.replace("@", fileExtension);
                        }
                        return rootFullPath + $scope.currentPaths.join('/') + "/" + file;
                    };

                    $scope.rootPath = function () {
                        $scope.currentPaths = [];
                        $scope.uploader.formData = [{
                            "filePath": $scope.currentPaths.join(',')
                        }];
                        $scope.selectItem = undefined;
                        $scope.loadChildFolders();
                        $scope.loadChildFiles();
                    };

                    $scope.switchPath = function ($index) {
                        if ($index == $scope.currentPaths.length - 1) return;
                        $scope.currentPaths = $scope.currentPaths.slice(0, $index);
                        $scope.uploader.formData = [{
                            "filePath": $scope.currentPaths.join(',')
                        }];
                        $scope.selectItem = undefined;
                        $scope.loadChildFolders();
                        $scope.loadChildFiles();
                    };


                    $scope.folderSelected = function (folder) {
                        $scope.currentPaths.push(folder);
                        $scope.uploader.formData = [{
                            "filePath": $scope.currentPaths.join(',')
                        }];
                        $scope.selectItem = undefined;
                        $scope.loadChildFolders();
                        $scope.loadChildFiles();
                    };


                    $scope.createFolder = function ($event) {
                        $event.stopPropagation();
                        var parentFolder = $scope.currentPaths.join(',');
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/index/views/index-resource-folder-edit.tpl.html',
                            controller: 'adResourceFolderEditController',
                            size: 'sm',
                            resolve: {
                                item: {}
                            }
                        });

                        modalInstance.result.then(function (data) {
                            var folderName = data;
                            service.folderCreate(parentFolder, folderName).then(function (data) {
                                var obj = angular.fromJson(data);
                                if (obj.result == 'success') {
                                    $scope.currentChildFolders = _.filter(obj.data, function (folder) {
                                        return folder.indexOf(deleteMark) == -1;
                                    });
                                }
                            });
                        }, function () {
                        });
                    };


                    $scope.editFolder = function (folder, $event) {
                        $event.stopPropagation();
                        var folderOldName = folder;
                        var parentFolder = $scope.currentPaths.join(',');
                        var modalInstance = $uibModal.open({
                            animation: true,
                            templateUrl: 'app/modules/index/views/index-resource-folder-edit.tpl.html',
                            controller: 'adResourceFolderEditController',
                            size: 'sm',
                            resolve: {
                                item: {
                                    folderName: folderOldName
                                }
                            }
                        });

                        modalInstance.result.then(function (data) {
                            var folderName = data;
                            service.folderRename(parentFolder, folderOldName, folderName).then(function (data) {
                                var obj = angular.fromJson(data);
                                if (obj.result == 'success') {
                                    $scope.currentChildFolders = _.filter(obj.data, function (folder) {
                                        return folder.indexOf(deleteMark) == -1;
                                    });
                                }
                            });
                        }, function () {
                        });
                    };

                    $scope.removeFolder = function (folder, $event) {
                        $event.stopPropagation();
                        var parentFolder = $scope.currentPaths.join(',');
                        service.folderDelete(parentFolder, folder).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.currentChildFolders = _.filter(obj.folders, function (folder) {
                                    return folder.indexOf(deleteMark) == -1;
                                });
                            }
                        });
                    };

                    $scope.removeFile = function (file, $event) {
                        $event.stopPropagation();
                        var parentFolder = $scope.currentPaths.join(',');
                        service.fileDelete(parentFolder, file).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.currentChildFiles = _.filter(obj.data, function (file) {
                                    return file.indexOf(deleteMark) == -1;
                                });
                            }
                        });
                    };

                    $scope.loadChildFolders = function () {
                        var parentFolder = $scope.currentPaths.join(',');
                        service.folderList(parentFolder).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.currentChildFolders = _.filter(obj.data, function (folder) {
                                    return folder.indexOf(deleteMark) == -1;
                                });
                            }
                        });
                    };

                    $scope.loadChildFiles = function () {
                        var parentFolder = $scope.currentPaths.join(',');
                        service.fileList(parentFolder).then(function (data) {
                            var obj = angular.fromJson(data);
                            if (obj.result == 'success') {
                                $scope.currentChildFiles = _.filter(obj.data, function (file) {
                                    return file.indexOf(deleteMark) == -1;
                                });
                            }
                        });
                    };

                    $scope.loadChildFolders();
                    $scope.loadChildFiles();

                    $scope.ok = function () {
                        $uibModalInstance.close($scope.currentPaths.join('/') + "/" + $scope.selectItem);
                    };

                    $scope.cancel = function () {
                        $uibModalInstance.dismiss('cancel');
                    };
                }]);
    });